// 比赛数据页面

import React, { useState, useEffect } from 'react';
import { getMatches } from '../../api/match';
import type { Match, MatchListParams } from '../../types/match';
import { handleApiError, getErrorMessage } from '../../utils/errorHandler';
import FootballAnimation from './components/FootballAnimation';
import FilterButtons from './components/FilterButtons';
import RecommendBadge from './components/RecommendBadge';
import BoldRecommendBadge from './components/BoldRecommendBadge';
import './MatchPage.css';

/**
 * 比赛数据页面组件
 * 显示今日比赛数据，支持分页和历史数据切换
 */
const MatchPage: React.FC = () => {
  // 状态管理
  const [matches, setMatches] = useState<Match[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [dateFilter, setDateFilter] = useState<'current' | 'historical'>('current');
  const [recommendationStatus, setRecommendationStatus] = useState<'all' | 'recommended' | 'pending'>('all');
  
  const pageSize = 10;

  // 获取比赛数据
  const fetchMatches = async (params: MatchListParams) => {
    try {
      setLoading(true);
      setError(null);
      
      // 只有当recommendationStatus不是'all'时才添加到参数中
      if (recommendationStatus !== 'all') {
        params.recommendationStatus = recommendationStatus as 'recommended' | 'pending';
      }
      
      const response = await getMatches(params);
      
      if (response.code === 0) {
        setMatches(response.data.data);
        setTotal(response.data.total);
        setCurrentPage(response.data.page);
        setTotalPages(response.data.totalPages);
      } else {
        setError(response.message || '获取数据失败');
      }
    } catch (err) {
      console.error('获取比赛数据失败:', err);
      
      // 使用统一的错误处理
      handleApiError(err);
      
      // 设置用户友好的错误信息
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchMatches({
      page: 1,
      pageSize,
      dateFilter
    });
  }, [dateFilter, recommendationStatus]);

  // 当筛选条件改变时重置到第一页
  useEffect(() => {
    if (currentPage !== 1) {
      setCurrentPage(1);
    }
  }, [dateFilter, recommendationStatus]);

  // 切换数据类型
  const handleDateFilterChange = (filter: 'current' | 'historical') => {
    setDateFilter(filter);
    setCurrentPage(1);
  };

  // 分页处理
  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
      fetchMatches({
        page,
        pageSize,
        dateFilter
      });
    }
  };

  // 生成分页按钮
  const renderPagination = () => {
    const pages = [];
    const maxVisiblePages = 5;
    
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 上一页按钮
    pages.push(
      <button
        key="prev"
        className="pagination-button"
        onClick={() => handlePageChange(currentPage - 1)}
        disabled={currentPage === 1}
      >
        上一页
      </button>
    );

    // 页码按钮
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          className={`pagination-button ${i === currentPage ? 'active' : ''}`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>
      );
    }

    // 下一页按钮
    pages.push(
      <button
        key="next"
        className="pagination-button"
        onClick={() => handlePageChange(currentPage + 1)}
        disabled={currentPage === totalPages}
      >
        下一页
      </button>
    );

    return pages;
  };

  return (
    <div className="match-page">
      {/* 页面头部 */}
      <div className="match-page__header">
        <div className="header-left">
          <FootballAnimation />
          <h1 className="match-page__title">今日比赛数据</h1>
        </div>
        
        <div className="header-filters">
          {/* 数据类型切换 */}
          <FilterButtons
            activeFilter={dateFilter}
            options={[
              { value: 'current', label: '今日比赛' },
              { value: 'historical', label: '历史比赛' }
            ]}
            onChange={(value) => handleDateFilterChange(value as 'current' | 'historical')}
            disabled={loading}
            dataActive={dateFilter}
            className="date-filter-group"
          />
          
          {/* 推荐状态筛选 */}
          <FilterButtons
            activeFilter={recommendationStatus}
            options={[
              { value: 'all', label: '全部' },
              { value: 'recommended', label: '已推荐' },
              { value: 'pending', label: '未推荐' }
            ]}
            onChange={(value) => setRecommendationStatus(value as 'all' | 'recommended' | 'pending')}
            disabled={loading}
            dataActive={recommendationStatus}
            className="recommendation-filter-group"
          />
        </div>
      </div>

      {/* 页面内容 */}
      <div className="match-page__content">
        {loading && (
          <div className="match-page__loading">
            正在加载比赛数据...
          </div>
        )}

        {error && (
          <div className="match-page__error">
            {error}
          </div>
        )}

        {!loading && !error && matches.length === 0 && (
          <div className="match-page__empty">
            暂无比赛数据
          </div>
        )}

        {!loading && !error && matches.length > 0 && (
          <>
            {/* 比赛表格 */}
            <div className="match-table-container">
              <table className="match-table">
                <thead>
                  <tr>
                    <th>竞彩编号</th>
                    <th>北单编号</th>
                    <th>比赛时间</th>
                    <th>联赛</th>
                    <th>主队 VS 客队</th>
                    <th>竞彩让球</th>
                    <th>北单让球</th>
                    <th>胜</th>
                    <th>平</th>
                    <th>负</th>
                    {/* 历史比赛才显示的投注结果列 */}
                    {dateFilter === 'historical' && (
                      <>
                        <th>主比分</th>
                        <th>客比分</th>
                        <th>赛果</th>
                        <th>是否命中</th>
                      </>
                    )}
                    <th>主队</th>
                    <th>客队</th>
                    <th>详情</th>
                  </tr>
                </thead>
                <tbody>
                  {matches.map((match) => 
                    match.bettings.length > 0 ? (
                      match.bettings.map((betting, index) => (
                        <tr key={`${match.id}-${betting.id}`} className={index === 0 ? 'first-betting' : 'additional-betting'}>
                          <td className="match-info jingcai-number">
                              {betting.jingcaiNumber || '-'}
                            </td>
                            <td className="match-info beidan-number">
                              {betting.beidanNumber || '-'}
                            </td>
                          {index === 0 && (
                            <>
                              <td rowSpan={match.bettings.length} className="match-info">
                                <div className="match-time">
                                  <div className="match-date">
                                    {new Date(match.matchTime).toLocaleDateString('zh-CN', {
                                      month: '2-digit',
                                      day: '2-digit'
                                    })}
                                  </div>
                                  <div className="match-weekday">
                                    {new Date(match.matchTime).toLocaleDateString('zh-CN', {
                                      weekday: 'short'
                                    })}
                                  </div>
                                  <div className="match-clock">
                                    {new Date(match.matchTime).toLocaleTimeString('zh-CN', {
                                      hour: '2-digit',
                                      minute: '2-digit',
                                      hour12: false
                                    })}
                                  </div>
                                </div>
                              </td>
                              <td rowSpan={match.bettings.length} className="match-info league">
                                {match.leagueName}
                              </td>
                              <td rowSpan={match.bettings.length} className="match-info teams">
                                <div className="teams-container">
                                  <span className="home-team">{match.homeTeam}</span>
                                  <span className="vs-text">VS</span>
                                  <span className="away-team">{match.awayTeam}</span>
                                </div>
                                <BoldRecommendBadge 
                                  boldRecommendation={match.boldRecommendation}
                                  show={!!match.boldRecommendation}
                                />
                              </td>
                            </>
                          )}
                          <td className="handicap">{betting.jingcaiHandicap || '-'}</td>
                          <td className="handicap beidan">{betting.beidanHandicap || '-'}</td>
                          <td className="odds win">
                            {betting.winOdds}
                            <RecommendBadge 
                              recommendType={betting.recommendedResult?.includes('win') ? 'win' : null} 
                              oddsType="win" 
                            />
                          </td>
                          <td className="odds draw">
                            {betting.drawOdds}
                            <RecommendBadge 
                              recommendType={betting.recommendedResult?.includes('draw') ? 'draw' : null} 
                              oddsType="draw" 
                            />
                          </td>
                          <td className="odds lose">
                            {betting.loseOdds}
                            <RecommendBadge 
                              recommendType={betting.recommendedResult?.includes('lose') ? 'lose' : null} 
                              oddsType="lose" 
                            />
                          </td>
                          {/* 历史比赛才显示的投注结果列 */}
                          {dateFilter === 'historical' && (
                            <>
                              <td className="match-result">
                                {betting.homeScore !== null ? betting.homeScore : '-'}
                              </td>
                              <td className="match-result">
                                {betting.awayScore !== null ? betting.awayScore : '-'}
                              </td>
                              <td className="match-result">
                                {betting.matchResult || '-'}
                              </td>
                              <td className="prediction-hit">
                                {betting.predictionHit === null ? '-' : 
                                 betting.predictionHit ? (
                                   <span className="hit-success">✓ 命中</span>
                                 ) : (
                                   <span className="hit-fail">✗ 未中</span>
                                 )
                                }
                              </td>
                            </>
                          )}
                          <td className="team-rate">{match.homeWinRate ? `${match.homeWinRate}%` : '-'}</td>
                          <td className="team-rate">{match.awayWinRate ? `${match.awayWinRate}%` : '-'}</td>
                          <td className="details">
                            <button className="detail-btn">详情</button>
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr key={match.id}>
                        <td>-</td>
                        <td>-</td>
                        <td>
                          <div className="match-time">
                            <div className="match-date">
                              {new Date(match.matchTime).toLocaleDateString('zh-CN', {
                                month: '2-digit',
                                day: '2-digit'
                              })}
                            </div>
                            <div className="match-weekday">
                              {new Date(match.matchTime).toLocaleDateString('zh-CN', {
                                weekday: 'short'
                              })}
                            </div>
                            <div className="match-clock">
                              {new Date(match.matchTime).toLocaleTimeString('zh-CN', {
                                hour: '2-digit',
                                minute: '2-digit',
                                hour12: false
                              })}
                            </div>
                          </div>
                        </td>
                        <td className="league">{match.leagueName}</td>
                        <td className="teams">
                          <div className="teams-container">
                            <span className="home-team">{match.homeTeam}</span>
                            <span className="vs-text">VS</span>
                            <span className="away-team">{match.awayTeam}</span>
                          </div>
                          <BoldRecommendBadge 
                            boldRecommendation={match.boldRecommendation}
                            show={!!match.boldRecommendation}
                          />
                        </td>
                        <td>-</td>
                        <td>-</td>
                        <td>-</td>
                        <td>-</td>
                        <td>-</td>
                        {/* 历史比赛才显示的投注结果列 */}
                        {dateFilter === 'historical' && (
                          <>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                          </>
                        )}
                        <td>{match.homeWinRate ? `${match.homeWinRate}%` : '-'}</td>
                        <td>{match.awayWinRate ? `${match.awayWinRate}%` : '-'}</td>
                        <td>
                          <button className="detail-btn">详情</button>
                        </td>
                      </tr>
                    )
                  )}
                </tbody>
              </table>
            </div>

            {/* 分页 - 始终显示 */}
            <div className="match-page__pagination">
              {renderPagination()}
              <div className="pagination-info">
                共 {total} 条数据，第 {currentPage} / {totalPages} 页
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default MatchPage;